/*
 * @Author: YeFei
 * @Date: 2021-11-09 10:03:03
 * @LastEditTime: 2021-12-06 14:26:56
 * @Descripttion:
 */
import XLSX from 'xlsx'
/**
 * @function 生成表格的方法
 * @param {String} excelName 文件名
 * @param {Array} titleArr 数据表头显示
 * @param {Array} dataArr 数据内容显示
 */

export default class ExcelUtil {
  static genTable (options) {
    new ExcelUtil(options)
  }

  constructor(options) {
    let filename = (options.excelName || new Date()) + ".xlsx" //文件名称
    let columns = options.columns || {}
    let tableData = options.tableData || []
    let filterKeys = options.filterKeys || ['action']
    let sheetName = options.sheetName || 'Sheet1'
    //拿到需要的列信息
    let columnsInfo = columns.filter(item => filterKeys.indexOf(item.key) === -1)
    //拿到key
    let columnsKeys = columnsInfo.map(item => item.key)
    //拿到title数组
    let titleArr = columnsInfo.map(item => item.title)
    //数据，一定注意需要时二维数组
    let data = [titleArr, ...this.getTableArr(tableData, columnsKeys)]
    let wb = XLSX.utils.book_new(),
      ws = XLSX.utils.aoa_to_sheet(data);
    XLSX.utils.book_append_sheet(wb, ws, sheetName)  //将数据添加到工作薄
    XLSX.writeFile(wb, filename)
  }

  getTableArr (tableData, columnsKeys) {
    let tableArr = []
    tableData.forEach((item) => {
      let itemArr = []
      columnsKeys.forEach((key) => {
        itemArr.push(item[key])
      })
      tableArr.push(itemArr)
    })
    return tableArr
  }
}









